package com.taijihuabao.common.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.util.CollectionUtils;
import com.taijihuabao.common.exception.ServiceException;
import com.taijihuabao.common.jsonresult.ApplicationResponseCode;
import com.taijihuabao.common.redisconfig.UserLoad;
import com.taijihuabao.modules.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Set;

/**
 * @author 拦截器
 */
public class TokenInter implements HandlerInterceptor {

    /**
     * 常量部分
     */
    private static final String TOKEN_NAME = "token";
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //公钥，前端传递
        String token = request.getHeader(TOKEN_NAME);
        //获取token并判断是否登录，未登录返回错误信息
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(ApplicationResponseCode.TOKEN_IS_NOT);
        }
        //是否过期，是否踢出
        Set<String> keys = redisTemplate.keys("UserLogin*");
        if (!CollectionUtils.isEmpty(keys)) {
            if (keys.contains(token)) {
                UserEntity userEntity = (UserEntity) redisTemplate.opsForValue().get(token);
                if (userEntity != null) {
                    long durationOutTime = 30L;
                    redisTemplate.opsForValue().set(token, userEntity, Duration.ofMinutes(durationOutTime));
                    UserLoad.setUser(userEntity);
                    return true;
                }
            } else {
                throw new ServiceException(ApplicationResponseCode.USER_LOGIN_KICK_OUT);
            }
        }
        throw new ServiceException(ApplicationResponseCode.TOKEN_EXPIRE);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
